package com.leetcode.partition8;

import com.leetcode.common.TreeNode;

/**
 * @author `RKC`
 * @date 2021/8/21 10:22
 */
public class LC701二叉搜索树中的插入操作 {

    public static TreeNode insertIntoBST(TreeNode root, int val) {
        return insert(root, val);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(5, new TreeNode(3), new TreeNode(10));
        root = insertIntoBST(root, 8);
        System.out.println(root.val);
    }

    private static TreeNode insert(TreeNode root, int val) {
        if (root == null) return new TreeNode(val);
        if (root.val > val) root.left = insert(root.left, val);
        else if (root.val < val) root.right = insert(root.right, val);
        return root;
    }

    private static TreeNode iteration(TreeNode root, int val) {
        if (root == null) return new TreeNode(val);
        TreeNode cur = root, parent = root;
        while (cur != null) {
            parent = cur;
            if (cur.val > val) cur = cur.left;
            else if (cur.val < val) cur = cur.right;
        }
        if (parent.val < val) parent.right = new TreeNode(val);
        else parent.left = new TreeNode(val);
        return root;
    }
}
